package com.zywl.web.controller.sys;

import com.zywl.core.beans.Resource;
import com.zywl.core.beans.User;
import com.zywl.service.ResourceService;
import com.zywl.utils.models.AjaxResult;
import com.zywl.utils.utils.Constants;
import com.zywl.utils.utils.enums.LogTypeEnum;
import com.zywl.utils.utils.enums.ResTypeEnum;
import com.zywl.utils.utils.enums.YesOrNoEnum;
import com.zywl.web.controller.base.BaseController;
import com.zywl.web.controller.form.ResourceForm;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/resource")
public class ResourceController extends BaseController {
    @Autowired
    private ResourceService resourceService;

    @GetMapping("/resourcePage")
    public ModelAndView resourcePage() {
        ModelAndView mav = new ModelAndView("resource/resourcePage");
        mav.addObject("resTypes", ResTypeEnum.values());
        return mav;
    }

    @PostMapping("/getResTree")
    public List<ResourceForm> getResTree(String enable) {
        List<Resource> resources = null;
        List<ResourceForm> resourceForms = new ArrayList<>();
        try {
            if (StringUtils.isNotEmpty(enable)) {
                resources = resourceService.getAllDataEnable("res_order desc");
            } else {
                resources = resourceService.getListAll("res_order desc");
            }
            for (Resource resource : resources) {
                ResourceForm resourceForm = new ResourceForm();
                resourceForm.setId(resource.getResId()+"");
                resourceForm.setpId(resource.getResPId()+"");
                resourceForm.setName(resource.getResName());
                resourceForm.setResType(resource.getResType());
                resourceForm.setResOrder(resource.getResOrder()+"");
                resourceForm.setResPath(resource.getResPath());
                resourceForm.setDescription(resource.getResDescription());
                resourceForm.setIcon(resource.getResIcon());
                resourceForm.setStatus(resource.getResStt());
                resourceForms.add(resourceForm);
            }
            if (resources != null) {
                ResourceForm resourceForm = new ResourceForm();
                resourceForm.setId(Constants.RESOURCE_ROOT_PARENT);
                resourceForm.setpId(String.valueOf(System.currentTimeMillis()));
                resourceForm.setName(Constants.RESOURCE_ROOT_PARENT_NAME);

                resourceForms.add(resourceForm);
            }
        } catch (Exception e) {
            logger.error("获取权限异常", e);
        }
        return resourceForms;
    }

    @PostMapping("/getAssResTree")
    public List<ResourceForm> getAssResTree(HttpServletRequest request) {
        List<Resource> resources = null;
        List<ResourceForm> resourceForms = new ArrayList<>();
        User user = (User) request.getSession().getAttribute(Constants.USER_SESSION_KEY);
        try {
            if (user.getUsrAssociationId() != null){
                resources = resourceService.getAllByAssId(user.getUsrAssociationId());
            }else{
                resources = resourceService.getAllDataEnable("res_order desc");
            }

            for (Resource resource : resources) {
                resource.setResIcon(null);
                ResourceForm resourceForm = new ResourceForm();
                resourceForm.setId(resource.getResId()+"");
                resourceForm.setpId(resource.getResPId()+"");
                resourceForm.setName(resource.getResName());
                resourceForm.setResType(resource.getResType());
                resourceForm.setResOrder(resource.getResOrder()+"");
                resourceForm.setResPath(resource.getResPath());
                resourceForm.setDescription(resource.getResDescription());
                resourceForm.setIcon(null);
                resourceForm.setStatus(resource.getResStt());
                resourceForms.add(resourceForm);
            }
            if (resourceForms != null) {
                ResourceForm resourceForm = new ResourceForm();
                resourceForm.setId(Constants.RESOURCE_ROOT_PARENT);
                resourceForm.setpId("0");
                resourceForm.setName(Constants.RESOURCE_ROOT_PARENT_NAME);

                resourceForms.add(resourceForm);
            }
        } catch (Exception e) {
            logger.error("获取权限异常", e);
        }
        return resourceForms;
    }

    @PostMapping("/resAddInit")
    public AjaxResult resAddInit(String id) {
        AjaxResult ar = new AjaxResult();
        if (Constants.RESOURCE_ROOT_PARENT.equals(id)) {
            ar.setInfo(Constants.RESOURCE_ROOT_PARENT_NAME);
        } else {
            try {
                Resource resource = resourceService.getById(Long.parseLong(id));
                if (resource != null) {
                    ar.setInfo(resource.getResName());
                }
            } catch (Exception e) {
                logger.error("获取权限异常", e);
            }
        }
        try {
            Integer resOrder = resourceService.getMaxOrderByPid(Long.parseLong(id));
            if (resOrder == null) {
                resOrder = 0;
            }
            ar.setObj(resOrder + 1);
        } catch (Exception e) {
            logger.error("获取权限最大值异常", e);
        }
        return ar;
    }

    @PostMapping("/resEditInit")
    public ResourceForm resEditInit(String id) {
        ResourceForm form = new ResourceForm();
        Resource resource = null;
        try {
            resource = resourceService.getById(Long.parseLong(id));
            form.setIcon(resource.getResIcon());
            form.setStatus(resource.getResStt());
        } catch (Exception e) {
            logger.error("获取权限异常", e);
        }
        String pId = resource.getResPId()+"";
        if (Constants.RESOURCE_ROOT_PARENT.equals(pId)) {
            form.setpName(Constants.RESOURCE_ROOT_PARENT_NAME);
        } else {
            try {
                resource = resourceService.getById(Long.parseLong(pId));
                if (resource != null) {
                    form.setpName(resource.getResName());
                }
            } catch (Exception e) {
                logger.error("获取权限异常", e);
            }
        }
        return form;
    }

    @PostMapping("/resourceSubmit")
    public AjaxResult resourceSubmit(HttpServletRequest request, ResourceForm form) {
        AjaxResult ar = new AjaxResult();
        Date date = new Date();
        try {
            Resource resource = new Resource();
//            BeanUtils.copyProperties(form, resource);
            resource.setResName(form.getName());
            resource.setResPId(Long.parseLong(form.getpId()));
            resource.setResType(form.getResType());
            resource.setResOrder(Integer.parseInt(form.getResOrder()));
            resource.setResPath(form.getResPath());
            resource.setResDescription(form.getDescription());
            resource.setResIcon(form.getIcon());
            resource.setResModifyTime(date);

            String id = form.getId();
            if (StringUtils.isEmpty(id)) {
                resource.setResCreateTime(date);
                resource.setResStt(YesOrNoEnum.YES.getKey());

                if (resourceService.permissionExist(resource.getResPath())) {
                    ar.error("该权限链接已被使用，请重新命名");
                    return ar;
                }

                resourceService.save(resource);
                ar.success("添加成功");
                saveLog(request, LogTypeEnum.RESOURCE.getKey(), "权限新增-" + form.getName());
            } else {
                Resource resourceOld = resourceService.getById(Long.parseLong(id));

                resource.setResId(Long.parseLong(id));
                resource.setResCreateTime(resourceOld.getResCreateTime());
                resource.setResStt(resourceOld.getResStt());
                resource.setResModifyTime(date);
                resourceService.update(resource);
                ar.success("修改成功");
                saveLog(request, LogTypeEnum.RESOURCE.getKey(), "权限修改-" + form.getName());
            }

            ar.setObj(resource.getResId());
        } catch (Exception e) {
            logger.error("权限提交异常", e);
            ar.error("权限提交异常", e);
        }
        return ar;
    }

    @PostMapping("/resDelete")
    public AjaxResult resDelete(HttpServletRequest request, String id) {
        AjaxResult ar = new AjaxResult();
        try {
            Resource resource = resourceService.getById(Long.parseLong(id));
            String resName = Constants.STRING_NULL;
            if (resource != null) {
                resName = resource.getResName();
            }
            resourceService.deleteById(Long.parseLong(id));
            saveLog(request, LogTypeEnum.RESOURCE.getKey(), "权限删除-" + resName);
            ar.success("删除成功");
        } catch (Exception e) {
            ar.error("删除权限异常", e);
            logger.error("删除权限异常", e);
        }
        return ar;
    }
}
